//
//  RHAddAssetSystemVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/12/31.
//

#import "RHAddAssetSystemVC.h"
#import "RHAddSystemCell.h"
#import "RHChoiceMultipleDeviceVC.h"
#import "RHAddCommonModel.h"
#import "ChoicePlantTypeView.h"

@interface RHAddAssetSystemVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) RHPlantTypeModel *curTypeModel;//当前选择的类型
@end

@implementation RHAddAssetSystemVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"添加系统".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
}

- (void)setupUI{
   
    [self createData];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHAddSystemCell class] forCellReuseIdentifier:@"RHAddSystemCell"];
    _tableView.layer.borderColor = kBorderColor.CGColor;
    _tableView.layer.borderWidth = 1;
    _tableView.layer.masksToBounds = YES;
    _tableView.layer.cornerRadius = 8;
    [self.view addSubview:_tableView];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [sureBtn setBackgroundColor:CMainColorGreen];
    sureBtn.titleLabel.font = kBOLDSYSTEMFONT(20);
    [sureBtn setCornerRadius:8];
    [sureBtn addTarget:self action:@selector(addSystem) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.height.offset(50);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.equalTo(sureBtn.mas_top).offset(-15);
    }];
    
}

-(void)addSystem
{
    [self.view endEditing:YES];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    for (RHAddCommonModel *model in self.dataArr) {
        if (model.isRequired) {
            if (model.content.length == 0) {
                [QMUITips showInfo:model.placeHolder];
                return;
            }
        }
        if (model.content.length>0 && model.key) {
            if ([model.tag isEqualToString:@"system_device"]) {
                [para setObject:model.deviceList forKey:model.key];
            }else{
                [para setObject:model.content forKey:model.key];
            }
        }
    }
    
   
   
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_assetSystemAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [kNotificationCenter postNotificationName:AssetSystemListNeedUpdateNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddCommonModel *model = self.dataArr[indexPath.row];
    if (indexPath.row == self.dataArr.count - 1) {
        model.isLast = YES;
    }
    RHAddSystemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAddSystemCell"];
    [cell setModel:model];
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    kWeakSelf;
 
    cell.clickBlock = ^{
        if([model.tag isEqualToString:@"system_device"]){
            [weakSelf.view endEditing:YES];
            [weakSelf getDeviceList:model];
        }else if([model.tag isEqualToString:@"device_type"]){
            [weakSelf.view endEditing:YES];
            [weakSelf selectDeviceType:model];
        }
        
        
    };
    return cell;
}

#pragma mark ----- 可添加的设备
-(void)getDeviceList:(RHAddCommonModel*)model
{
    if (!self.curTypeModel) {
        [QMUITips showInfo:@"请选择设备类型".rh_localized];
        return;
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(10000),
                           @"status":@"",
                           @"deviceTypeId":@(self.curTypeModel.typeId)
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_getSystemDeviceListCanAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            [self showDeviceList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];

}
-(void)showDeviceList:(NSArray*)deviceList  model:(RHAddCommonModel*)model
{
    RHChoiceMultipleDeviceVC *vc = [[RHChoiceMultipleDeviceVC alloc]init];
    vc.deviceList = deviceList;
    vc.curDevices = model.deviceList;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<NSString*> *arr) {
        model.deviceList = arr;
        model.content = [arr componentsJoinedByString:@","];
        [weakSelf.tableView reloadData];
    };
}

#pragma mark ------ 选择设备类型
-(void)selectDeviceType:(RHAddCommonModel*)plantModel
{
    kWeakSelf;
    [QMUITips showLoadingInView:self.view];
    [RHPlantTypeModel startGetWithCompletionAPIKey:H_plantTypeAndProductTypeRelation argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
    
            NSArray *plnatTypeArr = resultModel.data;
            
            ChoicePlantTypeView *choiceView = [[ChoicePlantTypeView alloc] init];
            choiceView.plantTypeList = plnatTypeArr;
            choiceView.curType = plantModel.content;
            [choiceView scorllToCurrentValue];
            [choiceView showAnimation];
        
            choiceView.choiceResultBlock = ^(RHPlantTypeModel * _Nonnull typeModel) {
                if (typeModel == nil) {
                    return;
                }
                weakSelf.curTypeModel = typeModel;
                plantModel.content = typeModel.plantType;
                [weakSelf.tableView reloadData];
            };
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)createData
{
   
    NSArray *datas = @[
        @{@"title":@"系统名称".rh_localized,
          @"placeHolder":@"请输入系统名称".rh_localized,
          @"isRequired":@(1),
          @"tag":@"system_name",
          @"isFirst":@(1),
          @"key":@"name"
        },
        @{@"title":@"设备类型".rh_localized,
          @"placeHolder":@"请选择设备类型".rh_localized,
          @"isRequired":@(1),
          @"isSelection":@(1),
          @"tag":@"device_type",
          @"key":@"systemType"
        },
        @{@"title":@"联系人".rh_localized,
          @"placeHolder":@"请输入联系人姓名".rh_localized,
          @"tag":@"system_contact_name",
          @"key":@"contact"
        },
        @{@"title":@"联系电话".rh_localized,
          @"placeHolder":@"请输入联系人电话".rh_localized,
          @"tag":@"system_contact_phone",
          @"key":@"contactNumber"
        },
        @{@"title":@"添加设备".rh_localized,
          @"placeHolder":@"请选择设备".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"system_device",
          @"isLast":@(1),
          @"key":@"deviceList"
        },
    ];
    
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHAddCommonModel class] json:datas];

}
@end
